<template>
  <div>
    <a-card>
      <a-form :form="form">
        <a-row :gutter="8">
          <a-col :md="8" :sm="12">
            <a-form-item
              label="开课院系"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select v-decorator="['kkyxm',
                {
                  rules: [{ required: true, message: '请选择培养单位!' }],
                }]" @change="yxChange" showSearch :filterOption="filterOption" :disabled="!!editId">
                <a-select-option v-for="i in selectMenu.yxList" :key="i.id" :value="i.dwh">{{ i.dwh }} {{ i.dwmc }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item
              label="课程名称"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select v-decorator="['kcbm',
                {
                  rules: [{ required: true, message: '请选择课程!' }],
                }]" @change="kcChange" showSearch :filterOption="filterOption" :disabled="!!editId">
                <a-spin v-if="kcLoading" slot="notFoundContent" size="small"/>
                <a-select-option v-for="(i,index) in selectMenu.courseList" :key="index" :value="i.kch">{{ i.kch }}{{ i.kcmc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item
              label="学分"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-input v-decorator="['xf']" disabled/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item
              label="上课年级"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select :disabled="!!last" v-decorator="['sknj',
                {
                  rules: [{ required: true, message: '请选择上课年级!' }],
                }]">
                <a-select-option v-for="i in TYPE0126" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item
              label="总学时"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-input v-decorator="['xs']" disabled/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item
              label="开课学年"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select :disabled="!!last" v-decorator="['kkxn',
                {
                  rules: [{ required: true, message: '请选择开课学年!' }],
                }]">
                <a-select-option v-for="i in TYPE0125" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item
              label="开课学期"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select :disabled="!!last" v-decorator="['kkxqm',
                {
                  rules: [{ required: true, message: '请选择开课学期!' }],
                }]">
                <a-select-option v-for="i in TYPE0072" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item
              label="上课类型"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select
              :disabled="!!last"
              @change="sklxChange"
              v-decorator="['sklxm',
                {
                  rules: [{ required: true, message: '请选择上课类型!' }],
                }]">
                <a-select-option v-for="i in TYPE0522" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12" v-if="itemShow">
            <a-form-item
              label="上课周类型"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select :disabled="!!last" v-decorator="['skzlxm',
                {
                  rules: [{ required: true, message: '请选择上课周类型!' }],
                }]">
                <a-select-option v-for="i in TYPE0343" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12" v-if="itemShow">
            <a-form-item
              label="上课周"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select :disabled="!!last" v-decorator="['skz',
                {
                  rules: [{ required: true, message: '请输入上课周!' }],
                }]">
                <a-select-option v-for="i in TYPE0344" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12" v-if="itemShow">
            <a-form-item
              label="开始课节"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select :disabled="!!last" v-decorator="['kskj',
                {
                  rules: [{ required: true, message: '请输入开始课节!' }],
                }]">
                <a-select-option v-for="i in TYPE0331.filter(i => i.code % 2 === 1)" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12" v-if="itemShow">
            <a-form-item
              label="结束课节"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select :disabled="!!last" v-decorator="['jskj',
                {
                  rules: [{ required: true, message: '请输入结束课节!' }],
                }]">
                <a-select-option v-for="i in TYPE0331.filter(i => i.code % 2 === 0)" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item
              label="开始周"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-input-number style="width: 100%" :max="99" :disabled="!!last" v-decorator="['ksz',
                {
                  rules: [{ required: true, message: '请输入开始周!' }],
                }]"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item
              label="结束周"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-input-number style="width: 100%" :max="99" :disabled="!!last" v-decorator="['jsz',
                {
                  rules: [{ required: true, message: '请输入结束周!' }],
                }]"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item
              label="班级名称"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-input :disabled="!!last" v-decorator="['jxbh',
                {
                  rules: [{ required: true, message: '请输入班级名称!' }],
                }]"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12" v-if="itemShow">
            <a-form-item
              label="最大选课人数限定"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-input-number style="width: 100%" :max="9999" v-decorator="['xkrsxd',
                {
                  rules: [{ required: true, message: '请输入最大选课人数!' },{validator:moreThanCapacity,trigger:'blur'} ],
                }]"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12" v-if="itemShow">
            <a-form-item
              label="最小选课人数限定"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-input-number style="width: 100%" :max="999" v-decorator="['xkrsxdMin',
                {
                  rules: [{ required: true, message: '请输入最小选课人数!' },{validator:moreThanCapacity,trigger:'blur'} ],
                }]"/>
            </a-form-item>
          </a-col>
          <a-col :md="16" :sm="24">
            <a-form-item
              label="备注"
              :labelCol="{span: 3,offset: 1}"
              :wrapperCol="{span: 17, offset: 1}"
            >
              <a-textarea :disabled="!!last" maxlength="500" v-decorator="['note']"/>
            </a-form-item>
          </a-col>
        </a-row>

        <template v-if="last">
          <a-card style="margin: 10px 0;">
            <h3>选择教师</h3>
            <a-row>
              <a-col :md="20" :sm="28">
                <a-row :gutter="8">
                  <a-col :md="8" :sm="12">
                    <a-form-item
                      v-bind="formItemLayout"
                      label="所属单位"
                    >
                <span class="ant-form-text">
                  {{ pkInfo.jsssyx }}
                </span>
                    </a-form-item>
                  </a-col>
                  <a-col :md="8" :sm="12">
                    <a-form-item
                      v-bind="formItemLayout"
                      label="教师"
                    >
                <span class="ant-form-text">
                  {{ pkInfo.rkjsmc }}
                </span>
                    </a-form-item>
                  </a-col>
                  <a-col :md="8" :sm="12">
                    <a-form-item
                      :labelCol="{span: 9,offset: 1}"
                      :wrapperCol="{span: 13, offset: 1}"
                      label="任课教师职工号"
                    >
                <span class="ant-form-text">
                  {{ pkInfo.rkjszgh }}
                </span>
                    </a-form-item>
                  </a-col>
                  <a-col :md="8" :sm="12">
                    <a-form-item
                      v-bind="formItemLayout"
                      label="教师职称"
                    >
                <span class="ant-form-text">
                  {{ pkInfo.jszcmc }}
                </span>
                    </a-form-item>
                  </a-col>
                  <a-col :md="12" :sm="20">
                    <a-form-item
                      label="任课教师说明"
                      :labelCol="{span: 5,offset: 1}"
                      :wrapperCol="{span: 16, offset: 1}"
                    >
                      <a-textarea maxlength="300" v-decorator="['rkjssm']"/>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-col>
              <a-col :md="4" :sm="8">
                <a-button type="primary" @click="showChoose('teacher')">选择教师</a-button>
              </a-col>
            </a-row>
          </a-card>

          <a-card v-if="itemShow">
            <h3>选择教室</h3>
            <a-row :gutter="8">
              <a-col :md="6" :sm="10">
                <a-form-item
                  v-bind="formItemLayout"
                  label="校区"
                >
                <span class="ant-form-text">
                  {{ pkInfo.xqmc }}
                </span>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="10">
                <a-form-item
                  v-bind="formItemLayout"
                  label="教室类型"
                >
                <span class="ant-form-text">
                  {{ pkInfo.jslxmc }}
                </span>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="10">
                <a-form-item
                  v-bind="formItemLayout"
                  label="教室"
                >
                <span class="ant-form-text">
                  {{ pkInfo.classroomNo }}
                </span>

                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="10">
                <a-form-item
                  v-bind="formItemLayout"
                  label="教室容量"
                >
                <span class="ant-form-text">
                  {{ pkInfo.capacity }}
                </span>

                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="10">
                <a-button type="primary" @click="showChoose('classroom')">选择教室</a-button>
              </a-col>
            </a-row>
          </a-card>

          <!-- <a-card style="margin-top: 10px;">
            <h3>添加听课学生</h3>
            <a-button type="primary" @click="showChoose('student')">选择学生</a-button>
          </a-card> -->
        </template>
        <div hidden></div>
        <a-form-item  :wrapperCol="{span: 39, offset: 5}" style="margin-top: 30px;">
          <a-button :loading="loading" type="primary" @click="toNext">{{ last ? '确定提交' : '下一步' }}</a-button>
          <a-button v-if="last" style="margin-left: 8px" @click="toLast">上一步</a-button>
          <a-button style="margin-left: 8px" @click="goBack">返回列表</a-button>
        </a-form-item>
      </a-form>
    </a-card>

<!--     <div class="ant-pro-footer-toolbar">
      <a-button style="float: right;margin-top: 10px;" @click="goBack">返回列表</a-button>

       <a-button style="margin-left: 50px;" type="primary" @click="toNext">{{ editId ? '提交保存' : '下一步' }}</a-button>
       <a-button style="float: right;margin-top: 10px;" @click="">{{'上一步'}}</a-button>
    </div>-->

    <choose-modal
      ref="choose"
      :visible="chooseVisible"
      :title="chooseTitle"
      :TYPE0126="TYPE0126"
      :type="chooseType"
      :editId="editId"
      :authYxList.sync="selectMenu.yxList"
      @cancel="chooseVisible = false"
      @updatePk="updatePk"/>

  </div>
</template>

<script>
import { mapState } from 'vuex'
import DetailList from '~/tool/DetailList'
import chooseModal from './components/chooesModal'
import ARow from "ant-design-vue/es/grid/Row";
import ACol from "ant-design-vue/es/grid/Col";
const DetailListItem = DetailList.Item

export default {
  data () {
    return {
      form: this.$form.createForm(this,{name:"form"}),
      selectMenu: {},
      kcLoading: false,
      chooseVisible: false,
      chooseType: null,
      chooseTitle: '',
      editId: null,
      last: false,
      loading: false,
      pkInfo: {xkrsxdMin: 3},
      formItemLayout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 14 },
      },
      itemShow:true,
    }
  },
  components: {ACol, ARow, DetailList, DetailListItem, chooseModal},
  computed: {
    ...mapState({
      TYPE0125: state => state.app['TYPE0125'],
      TYPE0126: state => state.app['TYPE0126'],
      TYPE0072: state => state.app['TYPE0072'],
      TYPE0343: state => state.app['TYPE0343'],
      TYPE0344: state => state.app['TYPE0344'],
      TYPE0522: state => state.app['TYPE0522'],
      TYPE0331: state => state.app['TYPE0331'] || [],
    })
  },
  created () {
    this.$store.dispatch('app/setDictionary', 'TYPE0125')
    this.$store.dispatch('app/setDictionary', 'TYPE0126')
    this.$store.dispatch('app/setDictionary', 'TYPE0072')
    this.$store.dispatch('app/setDictionary', 'TYPE0343')
    this.$store.dispatch('app/setDictionary', 'TYPE0344')
    this.$store.dispatch('app/setDictionary', 'TYPE0331')
    this.$store.dispatch('app/setDictionary', 'TYPE0522')
    this.initSelectMenu()
    if (this.$route.query.id) {
      this.editId = this.$route.query.id
      this.getInfo(this.editId)
    }else{
      this.form.setFieldsValue(this.pkInfo)
    }
  },
  methods: {
    initSelectMenu () {
      let allRequest = [
        this.$api.base.collegeAll()
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          yxList: res[0].data
        }
      })
    },
    getInfo (id) {
      this.$api.cultivate.pkDetail(id).then(res => {
        this.pkInfo = res.data
        let infoData = res.data
        if (infoData.kkyxm) {
          this.yxChange(infoData.kkyxm)
        }
        let keys = Object.keys(this.form.getFieldsValue())
        let obj = {}
        keys.forEach(key => {
          if(key == "sklxm"){
            if(infoData[key] == "01"){
              this.itemShow = true
            }else{
              this.itemShow = false
            }
            obj[key] = infoData[key]
          }else{
            obj[key] = infoData[key]
          }
        })
        this.form.setFieldsValue(obj)

      })
    },
    filterOption (value, op) {
      return op.componentOptions.children[0].text.indexOf(value) !== -1
    },
    sklxChange(code){
      if(code == "01"){
        this.itemShow = true
      }else{
        this.pkInfo.xqmc = ""
        this.pkInfo.jslxmc = ""
        this.pkInfo.classroomNo = ""
        this.pkInfo.capacity = ""
        this.form.resetFields(['skzlxm', 'skz', 'jskj', 'kskj', 'xkrsxdMin', 'xkrsxd'])
        this.itemShow = false
      }
      this.$forceUpdate()
    },
    yxChange (code) {
      this.form.setFieldsValue({kcbm: ''})
      this.$set(this.selectMenu, 'courseList', [])
      if (code) {
        this.kcLoading = true
        this.$api.cultivate.courseAll({kcssyxm: code}).then(res => {
          this.$set(this.selectMenu, 'courseList', res.data)
        }).finally(() => {
          this.kcLoading = false
        })
      } else {
        this.$set(this.selectMenu, 'courseList', [])
      }
    },
    kcChange (kch) {
      let kc = this.selectMenu.courseList.find(kc => {
        return kc.kch === kch
      })
      this.form.setFieldsValue({
        xs: kc.zxs,
        xf: kc.xf
      })
    },
    toLast () {
      this.last = false
    },
    toNext () {
      if(this.last){
        // if(!this.editId){
        //   this.$message.warning('课程信息主键丢失，请刷新浏览器后重试')
        //   return
        // }
        if(!this.pkInfo.rkjszgh){
          this.$message.warning('请选择任课教师')
          return
        }
        if(!this.pkInfo.classroomNo && this.itemShow){
          this.$message.warning('请选择教室')
          return
        }
        let apiFn = this.editId ? 'pkUpdate' : 'pkAdd'
        this.form.validateFields((err, values) => {
          if (err) {
            return;
          }
          const xkrsxd = this.form.getFieldValue('xkrsxd');
          const xkrsxdMin = this.form.getFieldValue('xkrsxdMin');
          if (xkrsxdMin > xkrsxd) {
            this.$message.error("最大选课人数必须大于等于最小选课人数")
            return;
          }
          if (xkrsxd > this.pkInfo.capacity) {
            this.$message.error("重新设置最大选课人数或者重新选择教室")
            return;
          }
          if (xkrsxdMin > this.pkInfo.capacity) {
            this.$message.error("重新设置最小选课人数或者重新选择教室")
            return;
          }
          let data = {
            ...values,
            id: this.editId,
            gh: this.pkInfo.rkjszgh,
            sm: this.form.getFieldValue('rkjssm'),
            classroomNo: this.pkInfo.classroomNo
          }
          if (!this.itemShow) {
            delete data.classroomNo
          }
          this.$api.cultivate[apiFn](data).then(res => {
            this.$message.success(res.msg)
            this.goBack()
          })
        })
        // this.$api.cultivate.saveTeacherAndClassroom({
        //   id: this.editId,
        //   gh: this.pkInfo.rkjszgh,
        //   sm: this.form.getFieldValue('rkjssm'),
        //   classroomNo: this.pkInfo.classroomNo
        // }).then(res => {
        //   this.$message.success(res.msg)
        //   this.goBack()
        // })
      } else {
        if (!this.editId) {
          this.form.validateFields((err, values) => {
            if (err) {
              return
            }
            // this.loading = true
            // this.$api.cultivate.pkAdd(values).then(res => {
            //   this.loading = false
            //   this.editId = res.data.id
            this.last = true
            //   this.$message.success(res.msg)
            // })
          })
        } else {
          this.form.validateFields((err, values) => {
            if (err) {
              return
            }
            this.last = true
          })
          // this.last = true
          // let reset = false
          // if(this.pkInfo.kkxn !== this.form.getFieldValue('kkxn')){
          //   reset = true;
          // }
          // if(this.pkInfo.kkxqm !== this.form.getFieldValue('kkxqm')){
          //   reset = true;
          // }
          // if(this.pkInfo.skzlxm !== this.form.getFieldValue('skzlxm')){
          //   reset = true;
          // }
          // if(this.pkInfo.skz !== this.form.getFieldValue('skz')){
          //   reset = true;
          // }
          // if(this.pkInfo.ksz !== this.form.getFieldValue('ksz')){
          //   reset = true;
          // }
          // if(this.pkInfo.jsz !== this.form.getFieldValue('jsz')){
          //   reset = true;
          // }
          // if(this.pkInfo.kskj !== this.form.getFieldValue('kskj')){
          //   reset = true;
          // }
          // if(this.pkInfo.jskj !== this.form.getFieldValue('jskj')){
          //   reset = true;
          // }
          // if(reset){
          //   this.$confirm({
          //     title: '提示?',
          //     content: '更新排课信息将清空已选任课教师、教室等信息，您确定要重新编辑吗？',
          //     centered: true,
          //     onOk: () => {
          //       this.postSave()
          //       this.pkInfo = {}
          //     },
          //     onCancel: () => {
          //     }
          //   })
          // }else{
          //   this.postSave()
          // }
        }
      }
    },
    postSave () {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        this.loading = true
        let params = Object.assign({
          id: this.editId
        }, values)
        this.$api.cultivate.pkUpdate(params).then(res => {
          this.loading = false
          this.last = true
          this.$message.success(res.msg)
        })
      })
    },
    showChoose(type) {
      this.$refs.choose.searchForm = Object.assign({}, this.form.getFieldsValue())
      // this.$refs.choose.teacherNote = this.pkInfo.rkjssm
      this.chooseVisible = true
      this.chooseType = type
      this.chooseTitle = (type === 'teacher' ? '选择教师' : '选择教室')
    },
    moreThanCapacity(rule, value, callback) {
      if (this.pkInfo.capacity && value > this.pkInfo.capacity) {
        callback("输入值不能大于教室最大容量值")
      }
      callback();
    },

    updatePk(data) {
      this.pkInfo = Object.assign(this.pkInfo, data);
      var params = ["xkrsxd", "xkrsxdMin"];
      this.form.validateFields(params, {}, (err, values) => {
        if (values["xkrsxd"] > data.capacity) {
          this.$message.error("重新设置最大选课人数或者重新选择教室")
        }
        if (values["xkrsxdMin"] > data.capacity) {
          this.$message.error("重新设置最小选课人数或者重新选择教室")
        }

      })
    },
    goBack() {
      this.$router.back()
    }
  }
}
</script>

<style>

</style>
